// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems: [], // 购物车中的商品列表
    totalPrice: 0 // 商品的总价格
  },
  getters: {
    cartItems: state => state.cartItems,
    totalPrice: state => state.totalPrice
  },
  mutations: {
    ADD_ITEM(state, item) {
      const existingItem = state.cartItems.find(cartItem => cartItem.id === item.id);
      if (existingItem) {
        existingItem.quantity += item.quantity;
      } else {
        state.cartItems.push(item);
      }
      state.totalPrice = state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
    },
    REMOVE_ITEM(state, id) {
      state.cartItems = state.cartItems.filter(item => item.id !== id);
      state.totalPrice = state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
    },
    UPDATE_QUANTITY(state, { id, quantity }) {
      const item = state.cartItems.find(item => item.id === id);
      if (item) {
        item.quantity = quantity;
        state.totalPrice = state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
      }
    }
  },
  actions: {
    addItem({ commit }, item) {
      commit('ADD_ITEM', item);
    },
    removeItem({ commit }, id) {
      commit('REMOVE_ITEM', id);
    },
    updateQuantity({ commit }, payload) {
      commit('UPDATE_QUANTITY', payload);
    }
  },
  modules: {}
})